package com.coffee.web;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author songkui
 * @since 2021-1-27 14:15
 */
@Configuration
public class CoffeeWebConfiguration {


    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;


    @Bean
    public CoffeeGlobalExceptionHandler globalExceptionHandler() {
        return new CoffeeGlobalExceptionHandler();
    }

    @Bean
    public CoffeeRunTimeLogsAspect coffeeRunTimeLogsAspect() {
        return new CoffeeRunTimeLogsAspect();
    }


    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
            builder.serializerByType(Long.class, ToStringSerializer.instance);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }

    @Bean
    public SpringContextBean SpringContextBean(){
        return new SpringContextBean();
    }
}